<template>
  <div class="database-main">
    <div class="header-actions">
      <h3>表详细信息</h3>
      <div class="view-controls">
        <el-switch
            v-model="isEditing"
            active-text="编辑模式"
            inactive-text="查看模式"
            @change="handleEditModeChange"
        />
        <el-switch
            v-if="!isEditing"
            v-model="isCompactView"
            active-text="精简模式"
            inactive-text="完整模式"
            style="margin-left: 10px"
        />
        <el-button
            v-if="isEditing"
            type="primary"
            size="small"
            @click="saveChanges"
            style="margin-left: 10px"
        >
          保存修改
        </el-button>
      </div>
    </div>

    <!-- 表基本信息展示 -->
    <div v-if="tableData" class="table-info">
      <el-descriptions column="4" border>
        <el-descriptions-item label="表ID">{{ tableData.tableId }}</el-descriptions-item>
        <el-descriptions-item label="表名">
          <template #default>
            <el-input
                v-if="isEditing"
                v-model="editableTableData.tableName"
                size="small"
                :disabled="!isEditing"
            />
            <span v-else>{{ tableData.tableName }}</span>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="数据库">{{ tableData.databaseName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" v-if="!isCompactView">{{ formatDate(tableData.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="4">
          <template #default>
            <el-input
                v-if="isEditing"
                v-model="editableTableData.description"
                type="textarea"
                size="small"
                :disabled="!isEditing"
                rows="2"
            />
            <span v-else>{{ tableData.description || '无描述信息' }}</span>
          </template>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 列信息表格 -->
    <div class="columns-section">
      <h4>表的所有列</h4>

      <el-table
          v-if="columns.length > 0"
          :data="editableColumns"
          border
          stripe
          :loading="columnsLoading"
          style="width: 100%; margin-top: 16px"
          tooltip-effect="dark"
      >
        <!-- 列ID：编辑/精简模式隐藏 -->
        <el-table-column
            prop="columnId"
            label="列ID"
            width="80"
            align="center"
            v-if="!isEditing && !isCompactView"
        />
        <el-table-column prop="columnName" label="列名" width="150">
          <template #default="scope">
            <el-input
                v-if="isEditing"
                v-model="scope.row.columnName"
                size="small"
                :disabled="!isEditing"
            />
            <span v-else>{{ scope.row.columnName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dataType" label="数据类型" width="120">
          <template #default="scope">
            <el-input
                v-if="isEditing"
                v-model="scope.row.dataType"
                size="small"
                :disabled="!isEditing"
            />
            <span v-else>{{ scope.row.dataType }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="columnPosition" label="位置" width="80" align="center" />
        <el-table-column prop="isPrimaryKey" label="主键" width="80" align="center">
          <template #default="scope">
            <el-select
                v-if="isEditing"
                v-model="scope.row.isPrimaryKey"
                size="small"
                :disabled="!isEditing"
            >
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
            <el-tag v-else :type="scope.row.isPrimaryKey === 1 ? 'success' : 'info'" size="small">
              {{ scope.row.isPrimaryKey === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isForeignKey" label="外键" width="80" align="center">
          <template #default="scope">
            <el-select
                v-if="isEditing"
                v-model="scope.row.isForeignKey"
                size="small"
                :disabled="!isEditing"
                @change="handleForeignKeyChange(scope.row)"
            >
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
            <el-tag v-else :type="scope.row.isForeignKey === 1 ? 'primary' : 'info'" size="small">
              {{ scope.row.isForeignKey === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 关联表ID：编辑/精简模式隐藏 -->
        <el-table-column
            prop="foreignTableId"
            label="关联表ID"
            width="100"
            align="center"
            v-if="!isEditing && !isCompactView"
        >
          <template #default="scope">
            <span>{{ scope.row.foreignTableId || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 关联表名：编辑模式下可修改（仅外键） -->
        <el-table-column prop="foreignTableName" label="关联表名" width="150">
          <template #default="scope">
            <el-input
                v-if="isEditing"
                v-model="scope.row.foreignTableName"
                size="small"
                :disabled="!isEditing || scope.row.isForeignKey !== 1"
                placeholder="请输入关联表名"
                clearable
            />
            <span v-else>{{ scope.row.foreignTableName || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 关联列ID：编辑/精简模式隐藏 -->
        <el-table-column
            prop="foreignColumnId"
            label="关联列ID"
            width="100"
            align="center"
            v-if="!isEditing && !isCompactView"
        >
          <template #default="scope">
            <span>{{ scope.row.foreignColumnId || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 关联列名：编辑模式下可修改（仅外键） -->
        <el-table-column prop="foreignColumnName" label="关联列名" width="150">
          <template #default="scope">
            <el-input
                v-if="isEditing"
                v-model="scope.row.foreignColumnName"
                size="small"
                :disabled="!isEditing || scope.row.isForeignKey !== 1"
                placeholder="请输入关联列名"
                clearable
            />
            <span v-else>{{ scope.row.foreignColumnName || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="isNullable" label="可为空" width="80" align="center">
          <template #default="scope">
            <el-select
                v-if="isEditing"
                v-model="scope.row.isNullable"
                size="small"
                :disabled="!isEditing"
            >
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
            <span v-else>{{ scope.row.isNullable === 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <!-- Java类型：编辑/精简模式隐藏 -->
        <el-table-column
            prop="javaType"
            label="Java类型"
            width="140"
            v-if="!isEditing && !isCompactView"
        >
          <template #default="scope">
            <span>{{ scope.row.javaType || '-' }}</span>
          </template>
        </el-table-column>
        <!-- 所属表名：编辑/精简模式隐藏 -->
        <el-table-column
            prop="tableName"
            label="所属表名"
            width="150"
            v-if="!isEditing && !isCompactView"
        >
          <template #default="scope">
            <span>{{ scope.row.tableName || '-' }}</span>
          </template>
        </el-table-column>
        <!-- 默认值：编辑/精简模式隐藏 -->
        <el-table-column
            prop="defaultValue"
            label="默认值"
            width="120"
            v-if="!isEditing && !isCompactView"
        >
          <template #default="scope">
            <span>{{ scope.row.defaultValue || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="列描述">
          <template #default="scope">
            <el-input
                v-if="isEditing"
                v-model="scope.row.description"
                size="small"
                :disabled="!isEditing"
                placeholder="请输入列描述"
            />
            <el-tooltip v-else :content="scope.row.description || '无描述'" placement="top">
              <div class="description-cell">{{ scope.row.description || '无描述' }}</div>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 外键描述：编辑模式下可修改（仅外键） -->
        <el-table-column prop="foreignKeyDescription" label="外键描述">
          <template #default="scope">
            <el-input
                v-if="isEditing"
                v-model="scope.row.foreignKeyDescription"
                size="small"
                :disabled="!isEditing || scope.row.isForeignKey !== 1"
                placeholder="请输入外键描述"
            />
            <el-tooltip v-else :content="scope.row.foreignKeyDescription || '无描述'" placement="top">
              <div class="description-cell">{{ scope.row.foreignKeyDescription || '无描述' }}</div>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 创建时间：编辑/精简模式隐藏 -->
        <el-table-column
            prop="createdAt"
            label="创建时间"
            width="180"
            v-if="!isEditing && !isCompactView"
        >
          <template #default="scope">{{ formatDate(scope.row.createdAt) }}</template>
        </el-table-column>

        <!-- 编辑模式下的操作列 -->
        <el-table-column
            label="操作"
            width="80"
            align="center"
            v-if="isEditing"
        >
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="handleDeleteColumn(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加列按钮 -->
      <el-button
          v-if="isEditing && props.tableData"
          type="success"
          size="small"
          style="margin-top: 10px"
          @click="handleAddColumn"
      >
        添加新列
      </el-button>

      <!-- 空状态展示 -->
      <div v-else-if="!columnsLoading" class="empty-tip">
        <el-empty description="暂无列信息" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElEmpty, ElSwitch, ElButton, ElInput, ElSelect, ElOption, ElTag, ElTooltip } from "element-plus";
import { watch, ref } from 'vue'
import { format } from 'date-fns'
import { useTableColumnsService } from "@/api/Table/TableColumnsApi.js"
import { useTableService } from "@/api/Table/TableApi.js";


// 定义列数据类型接口
interface ColumnItem {
  columnId: number | null
  tableId: number
  columnName: string
  dataType: string
  isNullable: 0|1        // 0-否 1-是
  isPrimaryKey: 0|1     // 0-否 1-是
  isForeignKey: 0|1     // 0-否 1-是
  foreignTableId: number | null
  foreignTableName: string | null
  foreignColumnName: string | null
  foreignColumnId: number | null
  description: string | null
  foreignKeyDescription: string | null
  createdAt: string|null
  javaType: string | null     // Java 映射类型
  tableName: string | null    // 冗余表名
  columnPosition: number       // 列位置序号
}

const props = defineProps<{
  tableData: {
    tableId: number
    tableName: string
    databaseName: string
    description?: string
    createdAt: string
  } | null
}>()
interface tableData {
  tableId: number
  tableName: string
  databaseName: string
  description?: string
}
// 状态定义
const isEditing = ref(false)
const isCompactView = ref(false)
const editableTableData = ref<any>({})
const editableColumns = ref<ColumnItem[]>([])
const originalTableData = ref<any>({})
const originalColumns = ref<ColumnItem[]>([])
// 列相关API
const { createTableColumns, updateTableColumn, deleteColumn } = useTableColumnsService()
const { getAllColumns,updateTable, loading: columnsLoading } = useTableService()
const columns = ref<ColumnItem[]>([])

// 获取列数据
const handleGetColumns = async () => {
  if (!props.tableData) return

  try {
    const response = await getAllColumns({
      tableId: props.tableData.tableId
    })
    columns.value = response.data.data || []
    originalColumns.value = JSON.parse(JSON.stringify(columns.value))
    editableColumns.value = JSON.parse(JSON.stringify(columns.value))
  } catch (error) {
    columns.value = []
    ElMessage.error('获取列数据失败')
  }
}

// 监听表格数据变化
watch(() => props.tableData, (newData) => {
  if (newData) {
    originalTableData.value = JSON.parse(JSON.stringify(newData))
    editableTableData.value = JSON.parse(JSON.stringify(newData))
    handleGetColumns()
  } else {
    columns.value = []
    editableColumns.value = []
    ElMessage.warning('请先选择有效的数据表')
  }
}, { immediate: true })

// 处理外键状态切换
const handleForeignKeyChange = (row: ColumnItem) => {
  // 强制触发响应式更新
  editableColumns.value = [...editableColumns.value]

  // 当外键从"是"改为"否"时，清空关联信息
  if (row.isForeignKey === 0) {
    row.foreignTableName = ''
    row.foreignColumnName = ''
    row.foreignKeyDescription = ''
    row.foreignTableId = null
    row.foreignColumnId = null
  } else {
    // 当切换为外键时，如果之前没有值则初始化
    if (row.foreignTableName === undefined) row.foreignTableName = ''
    if (row.foreignColumnName === undefined) row.foreignColumnName = ''
    if (row.foreignKeyDescription === undefined) row.foreignKeyDescription = ''
  }
}

// 处理编辑模式切换
const handleEditModeChange = (value: boolean) => {
  if (value) {
    editableTableData.value = JSON.parse(JSON.stringify(originalTableData.value))
    editableColumns.value = JSON.parse(JSON.stringify(originalColumns.value))
    ElMessage.info('进入编辑模式，可以修改表格数据')
  } else {
    ElMessage.info('退出编辑模式，未保存的修改将丢失')
  }
}

// 添加新列
const handleAddColumn = () => {
  if (!props.tableData) return

  const newColumn: ColumnItem = {
    columnId: null, // 新列ID为null
    tableId: props.tableData.tableId,
    columnName: '',
    dataType: '',
    isNullable: 1, // 默认可为空
    isPrimaryKey: 0, // 默认不是主键
    isForeignKey: 0, // 默认不是外键
    columnPosition: editableColumns.value.length + 1,
    createdAt: null,
    foreignTableId: null,
    foreignTableName: null,
    foreignColumnName:  null,
    foreignColumnId:  null,
    description: null,
    foreignKeyDescription:  null,
    javaType:  null,     // Java 映射类型
    tableName:  null,    // 冗余表名
  }

  editableColumns.value.push(newColumn)
  // 强制刷新表格
  editableColumns.value = [...editableColumns.value]
}

// 删除列
const handleDeleteColumn = (row: ColumnItem) => {
  const index = editableColumns.value.findIndex(col =>
      col.columnId === row.columnId &&
      col.columnName === row.columnName
  )

  if (index !== -1) {
    editableColumns.value.splice(index, 1)
    // 重新计算列位置
    editableColumns.value.forEach((col, idx) => {
      col.columnPosition = idx + 1
    })
  }
}

// 检查列是否被修改
const isColumnModified = (original: ColumnItem, edited: ColumnItem): boolean => {
  return original.columnName !== edited.columnName ||
      original.dataType !== edited.dataType ||
      original.isNullable !== edited.isNullable ||
      original.isPrimaryKey !== edited.isPrimaryKey ||
      original.isForeignKey !== edited.isForeignKey ||
      original.foreignTableName !== edited.foreignTableName ||
      original.foreignColumnName !== edited.foreignColumnName ||
      original.foreignKeyDescription !== edited.foreignKeyDescription ||
      original.description !== edited.description ||
      original.columnPosition !== edited.columnPosition;
}

// 筛选变化的列、删除的列和新增的列
const getChangedColumns = () => {
  const changedColumns: ColumnItem[] = []
  const deletedColumns: ColumnItem[] = []
  const newColumns: ColumnItem[] = []

  // 找出修改的列和新增的列
  editableColumns.value.forEach(editedCol => {
    // 新增列（没有columnId或columnId为null）
    if (!editedCol.columnId) {
      newColumns.push(editedCol)
    } else {
      const originalCol = originalColumns.value.find(col => col.columnId === editedCol.columnId)
      if (originalCol && isColumnModified(originalCol, editedCol)) {
        changedColumns.push(editedCol)
      }
    }
  })

  // 找出删除的列（原始有但编辑后没有）
  originalColumns.value.forEach(originalCol => {
    const exists = editableColumns.value.some(editedCol => editedCol.columnId === originalCol.columnId)
    if (!exists) {
      deletedColumns.push(originalCol)
    }
  })

  return { changedColumns, deletedColumns, newColumns }
}

// 处理删除的列
const handleDeletedColumns = async (deletedColumns: ColumnItem[]) => {
  if (deletedColumns.length === 0) return

  for (const col of deletedColumns) {
    try {
      await deleteColumn({
        columnId: col.columnId! })
      console.log(`列 ${col.columnName} 已删除`)
    } catch (error) {
      console.error(`删除列 ${col.columnName} 失败`, error)
      throw new Error(`删除列 ${col.columnName} 失败，请重试`)
    }
  }
}

// 处理修改的列
const handleChangedColumns = async (changedColumns: ColumnItem[]) => {
  if (changedColumns.length === 0) return

  for (const col of changedColumns) {
    try {
      await updateTableColumn({
        columnId: col.columnId!,
        columnName: col.columnName,
        dataType: col.dataType,
        isNullable: col.isNullable,
        isPrimaryKey: col.isPrimaryKey,
        isForeignKey: col.isForeignKey,
        foreignTableName: col?.foreignTableName,
        foreignColumnName: col?.foreignColumnName,
        foreignKeyDescription: col.foreignKeyDescription,
        description: col.description,
        columnPosition: col.columnPosition
      })
      console.log(`列 ${col.columnName} 已更新`)
    } catch (error) {
      console.error(`更新列 ${col.columnName} 失败`, error)
      throw new Error(`更新列 ${col.columnName} 失败，请重试`)
    }
  }
}

// 处理新增的列
const handleNewColumns = async (newColumns: ColumnItem[], tableData:tableData) => {
  if (newColumns.length === 0) return

  for (const col of newColumns) {
    try {
      //创建新的列
      await createTableColumns({
        databaseName: tableData.databaseName,
        tableName: tableData.tableName,
        columnName: col.columnName,
        dataType: col.dataType,
        isNullable: col.isNullable,
        isPrimaryKey: col.isPrimaryKey,
        isForeignKey: col.isForeignKey,
        foreignTableName: col.foreignTableName,
        foreignColumnName: col.foreignColumnName,
        foreignKeyDescription: col.foreignKeyDescription,
        description: col.description,
        columnPosition: col.columnPosition
      })
      console.log(`新增列 ${col.columnName} 成功`)
    } catch (error) {
      console.error(`新增列 ${col.columnName} 失败`, error)
      throw new Error(`新增列 ${col.columnName} 失败，请重试`)
    }
  }
}

//处理修改表
const handleUpdateTableData = async (tableData:tableData) => {
    try {
      await updateTable({
        tableId: tableData.tableId,
        tableName: tableData.tableName,
        databaseName: tableData.databaseName,
        description: tableData.description
      })
    } catch (error) {
      console.error(`修改表 ${tableData.tableName} 失败`, error)
      throw new Error(`修改表 ${tableData.tableName} 失败，请重试`)
      }
}
// 保存修改
const saveChanges = async () => {
  if (!props.tableData) {
    ElMessage.warning('请先选择有效的数据表')
    return
  }
 const tableData = props.tableData
  const { changedColumns, deletedColumns, newColumns } = getChangedColumns()
  if (changedColumns.length === 0 && deletedColumns.length === 0 && newColumns.length === 0) {
    ElMessage.info('没有需要保存的修改')
    isEditing.value = false
    return
  }

  try {
    //先处理修改表的操作
    await  handleUpdateTableData(tableData)
    // 先处理删除操作
    await handleDeletedColumns(deletedColumns)
    // 再处理修改操作
    await handleChangedColumns(changedColumns)
    // 最后处理新增操作
    await handleNewColumns(newColumns,tableData)
    // 刷新列数据
    await handleGetColumns()
    // 更新表格基本信息
    originalTableData.value = JSON.parse(JSON.stringify(editableTableData.value))

    isEditing.value = false
    ElMessage.success(`保存成功！`)
  } catch (error: any) {
    ElMessage.error(error.message || '保存失败，请重试')
    console.error('保存失败:', error)
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss')
}
</script>

<style scoped>
.database-main {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-controls {
  display: flex;
  align-items: center;
}

.table-info {
  margin-bottom: 20px;
}

.columns-section {
  margin-top: 20px;
}

h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #333;
}

.empty-tip {
  margin-top: 20px;
  padding: 40px 0;
  background-color: #fafafa;
  border-radius: 4px;
}

.description-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}
</style>